package com.fm.controller;

import com.fm.dto.MqttMsg;
import com.fm.dto.MqttSend;
import com.fm.entity.Equipment;
import com.fm.entity.Product;
import com.fm.entity.ProductFunction;
import com.fm.entity.TopicLog;
import com.fm.mqtt.ALink;
import com.fm.mqtt.MqttPushClient;
import com.fm.service.EquipmentService;
import com.fm.service.ProductFunctionService;
import com.fm.service.ProductService;
import com.fm.service.TopicLogService;
import com.fm.utils.JSONUtils;
import com.fm.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2018/8/13 0013.
 */
@RequestMapping("/api/mqtt")
@Controller
public class MqttController {

    @Autowired
    private EquipmentService equipmentService;
    @Autowired
    private ProductFunctionService productFunctionService;
    @Autowired
    private ProductService productService;
    @Autowired
    private SimpMessagingTemplate template;
    @Autowired
    private TopicLogService topicLogService;

    /**
     * 在线调试功能
     * @param param
     * @return
     */
    @RequestMapping(value = "/send", method = RequestMethod.POST)
    @ResponseBody
    public R send(@RequestBody MqttSend param) {
        Equipment equipment = equipmentService.selectOneByExample(param.getEqId()).get();
        Product product = productService.selectOneByExample(equipment.getProductId()).get();
        ProductFunction function = productFunctionService.selectOneByExample(param.getFunId()).get();
        MqttPushClient client = MqttPushClient.getInstance();
        String topic = "";
        String methods = "";
        ALink link = new ALink();
        link.setId(new Date().getTime()+"");
        link.setVersion("1.0");
        if (function.getType() == 1){//属性
            String method = param.getType()==1?"set":"get";
            topic = "sys/"+product.getProductKey()+"/"+equipment.getName()+"/thing/service/property/"+method;
            methods = "thing.service.property."+method;
        }else if (function.getType() == 2){//服务
            topic = "sys/"+product.getProductKey()+"/"+equipment.getName()+"/thing/service/"+function.getIdentifier();
            methods = "thing.service."+function.getIdentifier();
        }else if (function.getType() == 3){//事件
            topic = "sys/"+product.getProductKey()+"/"+equipment.getName()+"/thing/event/"+function.getIdentifier()+"/post";
            methods = "thing.event."+function.getIdentifier()+".post";
        }
        link.setParams(param.getParam());
        link.setMethod(methods);
        TopicLog log =  client.publish(param.getEqId(),topic,JSONUtils.toJSONString(link));
        if (param.getType() == 1) {
            template.convertAndSend("/topic/equipment/" + param.getEqId(), log);
        }
        return R.ok();
    }

    /**
     * 设备topic
     * @param param
     * @return
     */
    @RequestMapping(value = "/sendTopic", method = RequestMethod.POST)
    @ResponseBody
    public R sendTopic(@RequestBody MqttMsg param) {
        MqttPushClient client = MqttPushClient.getInstance();
        client.publish(param.getTopic(), param.getData(), param.getQos());
        return R.ok();
    }

    @RequestMapping(value = "/invoke")
    @ResponseBody
    public R invoke(String topic, ALink aLink) {
        MqttPushClient client = MqttPushClient.getInstance();
        try{
            String ts [] = topic.split("/");
            String eqName;
            if (ts[0].equals("sys")){
                eqName = ts[2];
            }else {
                eqName = ts[1];
            }
            Equipment equipment = equipmentService.getEquipmentByName(eqName);
            client.publish(equipment.getId(), topic, JSONUtils.toJSONString(aLink));
        }catch (Exception e) {
            return R.error("参数有误，请检查！");
        }
        return R.ok();
    }

    @RequestMapping(value = "/getPropertyValue")
    @ResponseBody
    public R getValue(String productKey, String deviceName, String propertyIdentifier, String url) {
        //根据设备名称获取设备，然后根据设备ID和产品ID获取第一条message
        Equipment equipment = equipmentService.getEquipmentByName(deviceName);
        TopicLog log = topicLogService.selectOneByEquipment(equipment.getId());
        if (log!=null){
            try{
                ALink link = JSONUtils.toBean(log.getContent(), ALink.class);
                Map<String, String> bean = link.getParams();
                Map<String, Object> remap = new HashMap();
                remap.put("attribute", propertyIdentifier);
                remap.put("batchId", new Date().getTime());
                remap.put("gmtModified", new Date().getTime());
                remap.put("iotId", new Date().getTime());
                remap.put("value", bean.get(propertyIdentifier));
                return R.ok().put("data", remap);
            }catch (RuntimeException e) {
                e.printStackTrace();

            }
        }
        return R.ok();
    }
}
